//
//  MultipleImagePickerViewController.m
//  YCSchool
//
//  Created by yanglinxia on 16/5/3.
//  Copyright © 2016年 yanglinxia. All rights reserved.
//  多图片选择视图控制器

#import "MultipleImagePickerViewController.h"
#import <AssetsLibrary/AssetsLibrary.h>
#import "MultipleImagePickerCell.h"
#import "AlbumPickerController.h"
#import "YCAssetsManager.h"
#import "UIImage+Photo.h"

NSString const * MutipleOriginImageKey = @"origin";
NSString const * MutipleThumbnailKey = @"thumbnail";

@interface MultipleImagePickerViewController ()<UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout>

///集合视图
@property (nonatomic, strong) UICollectionView *collectionView;
///图片资源数组
@property (nonatomic, strong) NSMutableArray *assets;
///相册分组
@property (nonatomic, strong) ALAssetsGroup *assetGroup;
///选择集合
@property (nonatomic, strong) NSMutableSet *selectedSet;
///工具栏
@property (nonatomic, strong) UIView *toolBar;
///数字标签视图
@property (nonatomic, strong) UILabel *numberLabel;
///提示标签视图
@property (nonatomic, strong) UILabel *tipLabel;
///最多可以选择的图片数量
@property (nonatomic, assign) NSUInteger maxNumberOfImages;
///选择的图片数组
@property (nonatomic, strong) NSMutableArray *selectedSetArray;

/// 取消回调
@property (nonatomic,copy) MultipleImagePickerControllerCancelBlock cancel;
/// 完成回调
@property (nonatomic,copy) MultipleImagePickerControllerCompletionBlock completion;




@end

@implementation MultipleImagePickerViewController


#pragma mark - 类方法

+ (void)presentMutipleImagePickerControllerAtViewController:(UIViewController *)viewController
                                maxNumberOfImages:(NSUInteger)maxNumberOfImages
                                completion:(MultipleImagePickerControllerCompletionBlock)completion
                                cancel:(MultipleImagePickerControllerCancelBlock)cancel
{
    AlbumPickerController *ablumController = [[AlbumPickerController alloc] initWithmaxNumberOfImages:maxNumberOfImages completion:completion cancel:cancel];
    
    MultipleImagePickerViewController *imagePickerController = [[MultipleImagePickerViewController alloc] initWithAssetGroup:nil
                                                    maxNumberOfImages:maxNumberOfImages
                                                           completion:completion
                                                                cancel:cancel];
    
    UINavigationController *nagigationController = [[UINavigationController alloc] init];
    nagigationController.viewControllers = @[ablumController,imagePickerController];
    [viewController presentViewController:nagigationController animated:YES completion:nil];
}

#pragma mark - 属性获取方法

- (UICollectionView *)collectionView
{
    if(!_collectionView)
    {
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        layout.scrollDirection = UICollectionViewScrollDirectionVertical;
        layout.minimumInteritemSpacing = 8;
        layout.minimumLineSpacing = 8;
        CGFloat kscreenW = [UIScreen mainScreen].bounds.size.width;
        CGFloat kscreenH = [UIScreen mainScreen].bounds.size.height;
        layout.itemSize = CGSizeMake((kscreenW - 5 * 8) / 4, (kscreenW - 5 * 8) / 4);
        layout.sectionInset = UIEdgeInsetsMake(0, 8, 0, 8);
        
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0,kscreenW, kscreenH - 47) collectionViewLayout:layout];
        _collectionView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
        _collectionView.dataSource = self;
        _collectionView.delegate = self;
        _collectionView.backgroundColor = [UIColor whiteColor];
        [_collectionView registerClass:[MultipleImagePickerCell class] forCellWithReuseIdentifier:@"cell"];
    }
    return _collectionView;
}

- (NSMutableArray *)assets
{
    if(!_assets)
    {
        _assets = [[NSMutableArray alloc] init];
    }
    return _assets;
}

- (NSMutableSet *)selectedSet
{
    if(!_selectedSet)
    {
        _selectedSet = [[NSMutableSet alloc] init];
    }
    return _selectedSet;
}


- (NSMutableArray *)selectedSetArray
{
    if(!_selectedSetArray)
    {
        _selectedSetArray = [[NSMutableArray alloc] init];
    }
    return _selectedSetArray;
}

- (UIView *)toolBar
{
    if(!_toolBar)
    {
        _toolBar = [[UIView alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height - 47, self.view.frame.size.width, 47)];
        _toolBar.autoresizingMask = UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleWidth;
        _toolBar.backgroundColor = [UIColor colorWithRed:238/255.0 green:238/255.0 blue:239/255.0 alpha:1];
        
        CGRect lRect,rRect;
        // 切割rect,右边宽为80  左边为宽-80
        CGRectDivide(_toolBar.bounds, &rRect, &lRect, 80, CGRectMaxXEdge);
        
        UIButton *finishButon = [[UIButton alloc] initWithFrame:CGRectInset(rRect, 10, 7)];
        [finishButon setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [finishButon setTitle:@"完成" forState:UIControlStateNormal];
        finishButon.titleLabel.font = [UIFont systemFontOfSize:18];
        [finishButon addTarget:self action:@selector(didTouchUpInsideFinishedButton:) forControlEvents:UIControlEventTouchUpInside];
        [_toolBar addSubview:finishButon];
        
        if(self.maxNumberOfImages < NSUIntegerMax)
        {
            CGRectDivide(CGRectInset(lRect, 12, 12), &lRect, &rRect, 47, CGRectMinXEdge);
            
            _numberLabel = [[UILabel alloc] initWithFrame:CGRectInset(lRect, 12, 0)];
            _numberLabel.backgroundColor = [UIColor blackColor];
            _numberLabel.textColor = [UIColor whiteColor];
            _numberLabel.layer.cornerRadius = 11.5;
            _numberLabel.layer.masksToBounds = YES;
            _numberLabel.textAlignment = NSTextAlignmentCenter;
            _numberLabel.text = @"0";
            [_toolBar addSubview:_numberLabel];
            
            _tipLabel = [[UILabel alloc] initWithFrame:rRect];
            _tipLabel.font = [UIFont systemFontOfSize:15];
            _tipLabel.textColor = [UIColor grayColor];
            _tipLabel.text = [NSString stringWithFormat:@"最多只能选择%ld张照片",self.maxNumberOfImages];
            [_toolBar addSubview:_tipLabel];
        }
    }
    return _toolBar;
}

#pragma mark - 生命周期

- (instancetype)initWithAssetGroup:(ALAssetsGroup *)group
                 maxNumberOfImages:(NSUInteger)maxNumberOfImages
                        completion:(MultipleImagePickerControllerCompletionBlock)completion
                            cancel:(MultipleImagePickerControllerCancelBlock)cancel
{
    if(self = [super init])
    {
        _assetGroup = group;
        _maxNumberOfImages = maxNumberOfImages;
        _completion = [completion copy];
        _cancel = [cancel copy];
    }
    return self;
}

- (void)setupNavBar
{
//    [self.navigationItem hidesBackButton];
//    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"PhotoNavBack"] style:UIBarButtonItemStylePlain target:self.navigationController action:@selector(popViewControllerAnimated:)];
//    self.navigationItem.leftBarButtonItem = leftItem;
    
    UIButton *stepTophotoAlbumBtn = [[UIButton alloc] init];
    [stepTophotoAlbumBtn setImage:[UIImage imageNamed:@"photoNavBack"] forState:UIControlStateNormal];
    stepTophotoAlbumBtn.titleLabel.font = [UIFont systemFontOfSize:14];
    [stepTophotoAlbumBtn setTitle:@"前往相册" forState:UIControlStateNormal];
    [stepTophotoAlbumBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    stepTophotoAlbumBtn.imageEdgeInsets = UIEdgeInsetsMake(0, -10, 0, 0);
    [stepTophotoAlbumBtn sizeToFit];
    [stepTophotoAlbumBtn addTarget:self.navigationController action:@selector(popViewControllerAnimated:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:stepTophotoAlbumBtn];
    self.navigationController.interactivePopGestureRecognizer.delegate = (id)self;
    
    // 取消
    UIButton *cancelButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [cancelButton setTitle:@"取消" forState:UIControlStateNormal];
    cancelButton.titleLabel.font = [UIFont systemFontOfSize:16];
    [cancelButton setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
    [cancelButton sizeToFit];
    [cancelButton addTarget:self action:@selector(didTouchUpInsideCancelBarButtonItem:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *rightBarButton = [[UIBarButtonItem alloc] initWithCustomView:cancelButton];
    self.navigationItem.rightBarButtonItem = rightBarButton;

}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self setupNavBar];
    [self.view addSubview:self.collectionView];
    [self.view addSubview:self.toolBar];
    
    //没有相册访问权限通知
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(showNotAllowed)
                                                 name:@"NotAllowedPhoto"
                                               object:nil];
    
    __weak typeof(self) weakSelf = self;
    
    ALAssetsGroupEnumerationResultsBlock assertEnumBlock = ^(ALAsset *result, NSUInteger index, BOOL *stop) {
        typeof(self) strongSelf = weakSelf;
        if([[result valueForProperty:ALAssetPropertyType] isEqualToString:ALAssetTypePhoto])
        {
            [strongSelf.assets addObject:result];
        }
    };
    
    void (^ assertEnumFinishBlock)(void) = ^{
        [self.collectionView reloadData];
        if(self.assets.count > 0)
        {
//            [self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:self.assets.count - 1 inSection:0] atScrollPosition:UICollectionViewScrollPositionBottom animated:NO];//停在底部
            [self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:UICollectionViewScrollPositionTop animated:NO];//停在顶部
        }
    };
    
    void (^ enumBlock)(void) = ^{
        if(!weakSelf) return;
        typeof(self) strongSelf = weakSelf;
        [strongSelf.assetGroup enumerateAssetsUsingBlock:assertEnumBlock];
        dispatch_async(dispatch_get_main_queue(), assertEnumFinishBlock);
    };
    
    if(self.assetGroup)
    {
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), enumBlock);
    }
    else
    {
        self.title = NSLocalizedString(@"所有照片", nil);
        _assetGroup = [YCAssetsManager shareManager].defaultAlbumGroup;
        if(self.assetGroup)
        {
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), enumBlock);
        }
        else
        {
            [[YCAssetsManager shareManager] loadAllAssetsGroupsCompletionBlock:^(YCAssetsManager *manager) {
                _assetGroup = manager.defaultAlbumGroup;
                dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), enumBlock);
            }];
        }
    }
}

#pragma mark - 没有访问权限提示
- (void)showNotAllowed {
    //没有权限时隐藏部分控件
//    self.toolBar.hidden = YES;
    self.navigationItem.title = @"无权限访问相册";
    UIAlertView *alert;
    if ([[[UIDevice currentDevice] systemVersion] floatValue] < 8.0) {
        alert = [[UIAlertView alloc] initWithTitle:@"提示"
                                           message:@"请在iPhone的“设置”-“隐私”-“照片”中，找到\"一乘驾校\"更改"
                                          delegate:nil
                                 cancelButtonTitle:@"确定"
                                 otherButtonTitles:nil, nil];
    } else {
        alert = [[UIAlertView alloc] initWithTitle:@"提示"
                                           message:@"请先前往设置允许访问照片"
                                          delegate:self
                                 cancelButtonTitle:@"取消"
                                 otherButtonTitles:@"前往", nil];
    }
    [alert show];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 1) {
        [[UIApplication sharedApplication] openURL:[NSURL  URLWithString:UIApplicationOpenSettingsURLString]];
    }
}

#pragma mark - 监听点击事件

- (void)didTouchUpInsideCancelBarButtonItem:(UIBarButtonItem *)backItem
{
    if(_cancel) _cancel();
    [self.navigationController dismissViewControllerAnimated:YES completion:nil];
}

- (void)didTouchUpInsideFinishedButton:(UIButton *)button
{
    NSMutableArray *images = [[NSMutableArray alloc] init];
    
    for (ALAsset *asset in self.selectedSetArray)
    {
        UIImage *originImage = [UIImage imageWithCGImage:[[asset defaultRepresentation] fullScreenImage]];
        originImage = [originImage photo_fixOrientationImage];
        [images addObject:@{MutipleThumbnailKey:[UIImage imageWithCGImage:asset.thumbnail],
                            MutipleOriginImageKey:originImage}];
    }
    
    if(_completion) _completion([[NSArray alloc] initWithArray:images]);
    [self.navigationController dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - UICollectionView datasource

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.assets.count;
}

#pragma mark - UICollectionView delegate

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    MultipleImagePickerCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    ALAsset *asset = self.assets[indexPath.row];
    UIImage *img = [UIImage imageWithCGImage:[asset thumbnail]];
    cell.contentView.layer.contents = (id)img.CGImage;
    cell.selectImageView.highlighted = [self.selectedSetArray containsObject:asset];
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    ALAsset *asset = self.assets[indexPath.row];
    MultipleImagePickerCell *cell = (MultipleImagePickerCell *)[collectionView cellForItemAtIndexPath:indexPath];
    BOOL selected = !cell.selectImageView.isHighlighted;
    if(selected)
    {
        if(self.selectedSetArray.count + 1 > self.maxNumberOfImages)
        {
            NSString *message = [NSString stringWithFormat:@"您最多只能选择%ld张照片",(unsigned long)self.maxNumberOfImages];
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:message delegate:nil cancelButtonTitle:@"知道了" otherButtonTitles:nil];
            [alertView show];
            return;
        }
        [self.selectedSetArray addObject:asset];
    }
    else
    {
        [self.selectedSetArray removeObject:asset];
    }
    cell.selectImageView.highlighted = selected;
    self.numberLabel.text = [NSString stringWithFormat:@"%ld",self.selectedSetArray.count];
}



@end
